package org.ladybug.spring.security;

import java.util.Iterator;

import org.springframework.security.Authentication;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.vote.AccessDecisionVoter;

public class LadybugAccessDecisionVoter implements AccessDecisionVoter {

	public boolean supports(ConfigAttribute attribute) {
		System.out.println("LadybugAccessDecisionVoter.supports()");
		System.out.println("ConfigAttribute: " + attribute);
		return true;
	}

	public boolean supports(Class clazz) {
		System.out.println("LadybugAccessDecisionVoter.supports()");
		System.out.println("Class: " + clazz);
		return true;
	}

	public int vote(Authentication authentication, Object object,
			ConfigAttributeDefinition config) {
		System.out.println("LadybugAccessDecisionVoter.vote()");
		System.out.println("Authentication: " + authentication);
		System.out.println("Object: " + object);
		System.out.println("ConfigAttributeDefinition: " + config);
		Iterator configAttributes = config.getConfigAttributes().iterator();
		while (configAttributes.hasNext()) {
			ConfigAttribute ca = (ConfigAttribute) configAttributes.next();
			GrantedAuthority[] ga = authentication.getAuthorities();
			if (ga == null) {
				return ACCESS_DENIED;
			}
			for (int i = 0; i < ga.length; i++) {
				String role = ca.getAttribute();
				if (role.equals(ga[i].getAuthority())) {
					return ACCESS_GRANTED;
				}
			}

		}
		return AccessDecisionVoter.ACCESS_DENIED;
	}

}
